<?php


namespace app\api\controller\points_mall;

use app\api\controller\xyb\Base;
use app\common\model\points_mall\Goods as GoodsModel;
use app\common\model\points_mall\Orders as OrdersModel;
use think\Cache;
use think\Db;


class Goods extends Base
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /*商品分类*/
    public function category()
    {
        $result = Db::name('points_mall_category')->field('id as value,name as label')
            ->where(['status'=>'normal'])->select();
        return json(['code'=>1,'msg'=>'获取成功','data'=>$result]);
    }

    /*商品列表*/
    public function promotion_lists()
    {
        $users = $this->getAuthUsers();
        $result = GoodsModel::getGoodsPromotionList($users->id);
        return json(['code'=>1,'msg'=>'获取成功','data'=>$result]);
    }

    /*商品详情*/
    public function details()
    {
        if(!$goods_id = (int)request()->param('goods_id')){
            return json(['code'=>0,'msg'=>'参数错误']);
        }
        $users = $this->getAuthUsers();
        if(!$result = GoodsModel::getGoodsPreviewDetails($goods_id)){
            return json(['code'=>0,'msg'=>'商品不存在']);
        }
        $result['exchange_status'] = GoodsModel::getUsersExchangeStatus($result, $users->id);
        $result['recommend'] = GoodsModel::getGoodsRecommend($goods_id, $users->id);
        return json(['code'=>1,'msg'=>'获取成功','data'=>$result]);
    }

    public function exchange()
    {
        if(!$goods_id = (int)request()->param('goods_id')){
            return json(['code'=>0,'msg'=>'参数错误']);
        }
        $cache_key = 'point_exchange_goods'.$goods_id;
        if(Cache::get($cache_key)){
            $this->error('太火爆了，请稍后再试');
        }
        /*查询商品信息*/
        if(!$result = GoodsModel::getGoodsPaymentDetails($goods_id)){
            return json(['code'=>0,'msg'=>'商品已售罄1']);
        }
        Cache::set($cache_key,1,60);
        $users = $this->getAuthUsers();

        $exchange_status = GoodsModel::getUsersExchangeStatus($result, $users->id);
        if(!$exchange_status || !isset($exchange_status['status'])){
            Cache::rm($cache_key);
            return json(['code'=>0,'msg'=>'商品已售罄2']);
        }
        if($exchange_status['status'] != 1){
            Cache::rm($cache_key);
            return json(['code'=>0,'msg'=>$exchange_status['text']]);
        }
        Db::startTrans();
        /*创建订单表*/
        if(!$order = OrdersModel::createGoodsOrder($result, $users->id)){
            Cache::rm($cache_key);
            Db::rollback();
            return json(['code'=>0, 'msg'=>'兑换失败1']);
        }
        if(!($order) || !isset($order->id) || !$order->id){
            Cache::rm($cache_key);
            Db::rollback();
            return json(['code'=>0, 'msg'=>'兑换失败12']);
        }
        $result['order_id'] = $order->id;
        /*发放奖励*/
        if(!$distribute = OrdersModel::distributeExchangeGoods($result, $users->id)){
            Cache::rm($cache_key);
            Db::rollback();
            return json(['code'=>0, 'msg'=>'兑换失败2']);
        }
        $result['distribute'] = $distribute;
        /*扣减用户积分 or 青年币*/
        if(!$payment = OrdersModel::processingUsersPaymentInformation($result, $users->id)){
            Cache::rm($cache_key);
            Db::rollback();
            return json(['code'=>0, 'msg'=>'兑换失败3']);
        }
        if($payment['stated'] == false || $payment['step'] == 0){
            Cache::rm($cache_key);
            Db::rollback();
            return json(['code'=>0, 'msg'=>'兑换失败4']);
        }
        if($payment['stated'] == true || $payment['step'] == 1){
            /*设置订单支付成功*/
            if(!OrdersModel::setOrdersPaymentSuccessful($result)){
                Cache::rm($cache_key);
                Db::rollback();
                return json(['code'=>0, 'msg'=>'兑换失败5']);
            }
        }
        /*销量加1*/
        GoodsModel::where('id', $goods_id)->setInc('sale_num');
        Cache::rm($cache_key);
        Db::commit();
        return json(['code'=>1,'msg'=>'兑换成功', 'data'=>[
            'order_id'          => $result['order_id'],
            'payment_step'      => $payment['step'],
            'payment_info'      => $payment['payment'],
            'payment_stated'    => $payment['stated'],
        ]]);
    }

    public function exchange_lists()
    {
        $page = (int)request()->param('page',1);
        $limit = (int)request()->param('limit', 10);
        $users = $this->getAuthUsers();
        $exchange_lists = OrdersModel::usersExchangeLists($users->id, $page, $limit);
        return json(['code'=>1,'msg'=>'获取成功','data'=>$exchange_lists]);
    }

    public function exchange_details()
    {
        if(!$order_id = (int)request()->param('order_id')){
            return json(['code'=>0,'msg'=>'参数错误']);
        }
        $exchange_lists = OrdersModel::usersExchangeDetails($order_id);
        return json(['code'=>1,'msg'=>'获取成功','data'=>$exchange_lists]);
    }

    public function exchange_chargeback()
    {
        if(!$order_id = (int)request()->param('order_id')){
            return json(['code'=>0,'msg'=>'参数错误']);
        }
        $response = OrdersModel::usersExchangeChargeback($order_id);
        return json($response);
    }

    /*用户兑换红包*/
    public function exchange_envelopes()
    {
        if(!$order_id = (int)request()->param('order_id')){
            return json(['code'=>0,'msg'=>'参数错误']);
        }
        $response = OrdersModel::usersExchangeEnvelopes($order_id);
        return json($response);
    }


}